<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import api from "@/api";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { ScriptTemplateSaveCmd } from "@/types";
import MonacoEditor from "@/components/monaco-editor/MonacoEditor.vue";

const monacoEditorRef = ref<InstanceType<typeof MonacoEditor>>();

const emit = defineEmits(["success"]);

const state = reactive({
  visible: false,
  form: new ScriptTemplateSaveCmd()
});

const title = computed(() => {
  return state.form.id ? "编辑脚本模板" : "新建脚本模板";
});

const formRef = ref<FormInstance | null>(null);

const rules: FormRules<ScriptTemplateSaveCmd> = reactive({
  name: [
    {
      required: true,
      message: "请输入",
      trigger: "blur"
    }
  ]
});

const submit = () => {
  formRef.value?.validate((valid, fields) => {
    if (valid) {
      api.scriptTemplate.saveScriptTemplate(state.form).then((res) => {
        ElMessage.success(res.message);
        emit("success");
        state.visible = false;
      });
    }
  });
};

const reset = () => {
  state.form = new ScriptTemplateSaveCmd();
  formRef.value?.resetFields();
};

const openDialog = (id?: string) => {
  state.visible = true;
  if (id) {
    // state.form.id = id;
    api.scriptTemplate.getScriptTemplate(id).then((data) => {
      state.form = data.data;
      monacoEditorRef.value?.setValue(state.form.script);
    });
  } else {
    monacoEditorRef.value?.setValue("");
  }
};

const closeDialog = () => {
  state.visible = false;
};

defineExpose({
  openDialog,
  closeDialog
});
</script>

<template>
  <el-dialog v-model="state.visible" :title="title" :close-on-click-modal="false" @open="reset">
    <div>
      <el-form :model="state.form" label-width="auto" ref="formRef" :rules="rules">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="state.form.name" />
        </el-form-item>
        <el-form-item label="模板标签">
          <el-input v-model="state.form.tag" />
        </el-form-item>
        <el-form-item label="模板脚本">
          <div h-400px w-full>
            <monaco-editor
              ref="monacoEditorRef"
              @change="(val: string) => (state.form.script = val)"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="state.visible = false">取消</el-button>
        <el-button type="primary" @click="submit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="css" scoped></style>
